package version3.part2.Client.Cache;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ServiceCache {
    // String: service name, List<String>: list of servers
    private static Map<String, List<String>> cache =new HashMap<>();

    // 增
    public void addService(String serviceName, String address) {
        List<String> list = cache.get(serviceName);
        if (list == null) {
            list = new ArrayList<>();
            list.add(address);
            System.out.println("新增服务，服务名称：" + serviceName + "，服务地址：" + address);
            cache.put(serviceName, list);
        }else{
            list.add(address);
            System.out.println("新增服务，服务名称：" + serviceName + "，服务地址：" + address);
        }
    }
    // 删
    public void removeService(String serviceName, String address) {
        List<String> list = cache.get(serviceName);
        if (list != null) {
            list.remove(address);
            System.out.println("删除服务，服务名称：" + serviceName + "，服务地址：" + address);
        }
    }
    // 改
    public void updateService(String serviceName, String oldAddress, String newAddress) {
        List<String> list = cache.get(serviceName);
        if (list != null) {
            list.remove(oldAddress);
            list.add(newAddress);
            System.out.println("更新服务，服务名称：" + serviceName + "，旧服务地址：" + oldAddress + "，新服务地址：" + newAddress);
        }else{
            System.out.println("服务不存在，服务名称：" + serviceName + "，服务地址：" + oldAddress);
        }
    }
    // 查
    public List<String> getService(String serviceName) {
        return cache.get(serviceName);
    }

}
